package com.picket.dao;

import java.util.Collection;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.orm.jdo.support.JdoDaoSupport;
import org.springframework.stereotype.Repository;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.picket.domain.Pool;

@Repository
public class PoolDao extends JdoDaoSupport implements IPoolDao {

	@Override
	public Pool create(final Pool pool) {
		getJdoTemplate().makePersistent(pool);
		return pool;
	}

	@Override
	public Collection<Pool> getAllPools() {

		final PersistenceManager pm = getPersistenceManager();

		try {

			final Query query = pm.newQuery(Pool.class);

			@SuppressWarnings("unchecked")
			final Collection<Pool> pools = (Collection<Pool>) query.execute();

			return pm.detachCopyAll((Collection<Pool>) pools);
		}

		finally {
			releasePersistenceManager(pm);
		}

	}

	@Override
	public Pool getPool(long id) {

		final PersistenceManager pm = getPersistenceManager();

		try {

			Key k = KeyFactory.createKey(Pool.class.getSimpleName(), id);
			return pm.getObjectById(Pool.class, k);
		}

		finally {
			releasePersistenceManager(pm);
		}

	}

	@Override
	public Collection<Pool> getAllPoolsForEvent(long eventId) {

		final PersistenceManager pm = getPersistenceManager();

		try {

			final Query query = pm.newQuery(Pool.class);
			query.setFilter("eventId == eventIdParam");
			query.declareParameters("long eventIdParam");
			@SuppressWarnings("unchecked")
			final Collection<Pool> pools = (Collection<Pool>) query
					.execute(eventId);

			return pm.detachCopyAll((Collection<Pool>) pools);
		}

		finally {
			releasePersistenceManager(pm);
		}

	}

	@Override
	public Pool findByReferral(String referralKey) {
		final PersistenceManager pm = getPersistenceManager();

		try {

			final Query query = pm.newQuery(Pool.class);
			query.setFilter("referralKey == referralKeyParam");
			query.declareParameters("String referralKeyParam");
			final Collection<Pool> pools = (Collection<Pool>) query.execute(referralKey);
			
			Object[] opools = pm.detachCopyAll((Collection<Pool>) pools).toArray();
			if(opools.length == 0)
				return null;
			else
				return (Pool)opools[0];
		}

		finally {
			releasePersistenceManager(pm);
		}
	}
}